﻿using ConfExpert.Forms.Base;
using DevExpress.Utils;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraVerticalGrid.Rows;
using DevTeam;

using System;
using System.Drawing;
using System.Windows.Forms;

namespace ConfExpert.Forms.Depo.Aksesuar
{
    public partial class FaturaGiris : XForm
    {
        public FaturaGiris()
        {
            InitializeComponent();
        }

        private void FaturaGiris_Load(object sender, EventArgs e)
        {
            
            gvAksPOFatura.Init("GetAllAksesuarGirisForInvoice", "", 0, DateTime.Now.AddDays(-7), DateTime.Now, "", 0);
            gvAksPOFatura.AddDetailGrid(gvAksPOFaturaLines, "AksesuarGirenPartiId", 1);

            gvAksPOFaturaLines.AddColumn("Tutar", typeof(decimal), "GelenAdet*Isnull(BirimFiyat,0)");
            gvAksPOFatura.AddColumn("AksesuarFiyatToplam", typeof(decimal), "SUM(Child({FK}).Tutar)", 0);
            gvAksPOFatura.AddColumn("ToplamTutar", typeof(decimal), "Isnull(AksesuarFiyatToplam,0)");

            gvAksPOFatura.MakeColumnInvisible("AksesuarFiyatToplam");
            gvAksPOFaturaLines.MakeColumnInvisible("AksesuarGirenPartiId");

            gvAksPOFaturaLines.FormatAsNumber(0, "GelenAdet");
            gvAksPOFaturaLines.FormatAsNumber(2, "Tutar");
            gvAksPOFatura.FormatAsNumber(2, "ToplamTutar", "FaturaMaliyet");

            gvAksPOFatura.AddSummary("ToplamTutar");
            gvAksPOFaturaLines.AddSummary("GelenAdet", "Tutar");

            gvAksPOFatura.MakeReadOnly("FaturaNo");
            gvAksPOFaturaLines.MakeReadOnly("BirimFiyat");

            gvAksPOFatura.SetCaptions("AksesuarGirenPartiId:GirisPartisi", "UserId:Giren", "CariId:Üretici");

            btnTemizle.Click += new EventHandler(btnTemizle_Click);
            btnGetir.Click += btnGetir_Click;

            CreateVerticalGrid();

            gvAksPOFatura.OptionsView.AllowCellMerge = true;                       

            gvAksPOFatura.BestFitColumns();
            gvAksPOFaturaLines.BestFitColumns();

            bbiSave.ItemClick += bbiSave_ItemClick;
            gvAksPOFatura.MouseMove += gvAksPOFatura_MouseMove;
            gvAksPOFatura.RowCellClick += gvAksPOFatura_RowCellClick;
            gvAksPOFatura.RowCellStyle += gvAksPOFatura_RowCellStyle;
            gvAksPOFatura.CellMerge += gvAksPOFatura_CellMerge;
        }

        void gvAksPOFatura_CellMerge(object sender, DevExpress.XtraGrid.Views.Grid.CellMergeEventArgs e)
        {
            GridView view = sender as GridView;
            e.Merge = view.GetRowCellDisplayText(e.RowHandle1, e.Column) == view.GetRowCellDisplayText(e.RowHandle2, e.Column) &&
                e.Column.FieldName=="FaturaMaliyet" &&
                view.GetRowCellDisplayText(e.RowHandle1, "FaturaNo") == view.GetRowCellDisplayText(e.RowHandle2, "FaturaNo");

            e.Handled = true;

        }

        void gvAksPOFatura_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {            
            if (e.RowHandle > -1 && e.Column.FieldName == "FaturaNo")
            {
                e.Appearance.Font = new Font(AppearanceObject.DefaultFont, FontStyle.Underline);
                e.Appearance.ForeColor = Color.Blue;
            }
        }

        void gvAksPOFatura_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            int faturaNo = gvAksPOFatura.GetRowCellValue(e.RowHandle, "FaturaNo").ToInt();
            if (e.RowHandle > -1 && e.Column.FieldName == "FaturaNo" && faturaNo > 0)
            {
                AksPOFaturaLines fatura = new AksPOFaturaLines(faturaNo.ToString());
                DialogResult dr = fatura.ShowDialog();

                if (dr==DialogResult.OK)
                {
                    Yenile();
                }
            }
        }

        void gvAksPOFatura_MouseMove(object sender, MouseEventArgs e)
        {
            var hitInfo = gvAksPOFatura.CalcHitInfo(e.Location);
            if (hitInfo.InRowCell)
            {
                int rowHandle = hitInfo.RowHandle;
                int faturaNo = gvAksPOFatura.GetRowCellValue(rowHandle, "FaturaNo").ToInt();
                GridColumn column = hitInfo.Column;
                if (column.FieldName == "FaturaNo" && faturaNo>0)
                    this.Cursor = Cursors.Hand;
                else
                    this.Cursor = Cursors.Default;
            }
        }

        void btnGetir_Click(object sender, EventArgs e)
        {
            Yenile();            
        }

        private void Yenile()
        {
            gvAksPOFatura.EndEditing();
            gvAksPOFaturaLines.EndEditing();

            if (gvAksPOFatura.Dataset().HasChanges())
            {
                if (XtraMessageBox.Show("Formdaki veriler yenilenecek. Form yenilenmeden önce kaydetmediğiniz verileri kaydetmek ister misiniz ?", "Kritik!", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {
                    bbiSave.PerformClick();
                }
            }

            gvAksPOFatura.RefreshDataSource("GetAllAksesuarGirisForInvoice",
                strParse(GetVal("BelgeNo")),
                intParse(GetVal("Tedarikçi")),
                datetimeParse(GetVal("BaslangicTarihi")),
                datetimeParse(GetVal("BitisTarihi")),
                strParse(GetVal("Aciklama")),
                intParse(GetVal("AksesuarId"))
                );
            Notify("Done.");
        }

        void bbiSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            gvAksPOFatura.EndEditing();
            gvAksPOFaturaLines.EndEditing();

            if (gvAksPOFatura.Dataset().HasChanges())
            {
                string xml = gvAksPOFaturaLines.SerializeChanges();

                gvAksPOFatura.Update("AksesuarGirenPartiId,FaturaNo", "AksesuarGirenParti");
                ExecuteNonQuery("UpdAksesuarBirimFiyat", xml);
            }

            //btnGetir.PerformClick();
        }

        private void CreateVerticalGrid()
        {
            vgc.Rows.AddRange(new BaseRow[] {
                AddItem("BelgeNo", typeof(string)),
                AddItem("Tedarikçi", typeof(int), RI(Rp.Vendor)),
                AddItem("BaslangicTarihi", typeof(DateTime), new RepositoryItemDateEdit()),
                AddItem("BitisTarihi", typeof(DateTime), new RepositoryItemDateEdit()),
                AddItem("Aciklama", typeof(string), new RepositoryItemMemoEdit()),
                AddItem("AksesuarId", typeof(int), RI(Rp.V_Aksesuar))
            });

            vgc.Rows.GetRowByFieldName("Aciklama", true).Height = 60;

            vgc.OptionsBehavior.UseEnterAsTab = true;
            vgc.LayoutStyle = DevExpress.XtraVerticalGrid.LayoutViewStyle.SingleRecordView;
            vgc.CustomDrawRowHeaderCell += vgc_CustomDrawRowHeaderCell;
            vgc.Appearance.RowHeaderPanel.BackColor = Color.LightBlue;

            vgc.SetCellValue(vgc.Rows["BaslangicTarihi"], 0, DateTime.Now.AddDays(-7));
            vgc.SetCellValue(vgc.Rows["BitisTarihi"], 0, DateTime.Now);

            vgc.FocusedRow = vgc.Rows["BelgeNo"];
            vgc.BestFit();
        }

        public BaseRow AddItem(string name, Type t, params RepositoryItem[] ri)
        {
            return AddItem(vgc, name, t, ri);
        }

        object GetVal(string FieldName)
        {
            return vgc.GetCellValue(vgc.Rows[FieldName], vgc.FocusedRecord);
        }

        void btnTemizle_Click(object sender, EventArgs e)
        {
            foreach (BaseRow r in vgc.Rows)
                vgc.SetCellValue(r, 0, null);
        }

        private void dockPanel1_Click(object sender, EventArgs e)
        {

        }
    }
}